<template>
  <div class="xtx-pagination">
    <a v-if="myCurrentPage === 1" href="javascript:;" class="disabled">上一页</a>
    <a @click="changePage(myCurrentPage - 1)" v-else href="javascript:;">上一页</a>
    <span v-if="pager.start > 1">...</span>
    <a @click="changePage(item)" v-for="item in pager.pageArr" :key="item" href="javascript:;"
      :class="{ active: item === myCurrentPage }">{{ item }}</a>
    <span v-if="pager.stop < pager.totalPages">...</span>
    <a v-if="myCurrentPage >= pager.totalPages" href="javascript:;" class="disabled">下一页</a>
    <a @click="changePage(myCurrentPage + 1)" v-else href="javascript:;">下一页</a>
  </div>
</template>
<script>
import { computed, ref, watch } from 'vue'
export default {
  name: 'XtxPagination',
  props: {
    currentPage: {
      type: Number,
      default: 1
    },
    pageSize: {
      type: Number,
      default: 10
    },
    total: {
      type: Number,
      default: 100
    }
  },
  setup(props, { emit }) {
    // 总记录数
    const myTotal = ref(100)
    // 每页显示的条数
    const myPageSize = ref(10)
    // 当前页码
    const myCurrentPage = ref(1)
    // 按钮个数
    const btnCount = 5
    // 侦听父组件props数据的变化，改变当前组件相关的数据
    watch(props, () => {
      myTotal.value = props.total
      myPageSize.value = props.pageSize
      myCurrentPage.value = props.currentPage
    }, { immediate: true })

    // 根据以上数据构建分页字符串对象
    const pager = computed(() => {
      // 获取总页数
      const totalPages = Math.ceil(myTotal.value / myPageSize.value)
      // 起始页码和结束页码
      // 正常情况下：理想情况，左右两边...，上一页和下一页都可点
      let start = myCurrentPage.value - Math.floor(btnCount / 2)
      let stop = start + btnCount - 1
      // 临界状态
      if (start < 1) {
        start = 1
        // 如果结束位置计算的结构超过了总页数
        stop = (start + btnCount - 1) > totalPages ? totalPages : (start + btnCount - 1)
      }
      if (stop > totalPages) {
        stop = totalPages
        start = (stop - btnCount + 1) < 1 ? 1 : (stop - btnCount + 1)
      }
      // 形成一个开始和结束位置的数组
      const pageArr = []
      for (let i = start; i <= stop; i++) {
        pageArr.push(i)
      }
      // 返回对象
      return {
        start,
        stop,
        pageArr,
        totalPages
      }
    })
    // 改变页码
    const changePage = (page) => {
      myCurrentPage.value = page
      // 提供一个修改页码的自定义事件
      emit('change-current', page)
    }
    return { pager, myCurrentPage, changePage }
  }
}
</script>
<style scoped lang="less">
.xtx-pagination {
  display: flex;
  justify-content: center;
  padding: 30px;

  >a {
    display: inline-block;
    padding: 5px 10px;
    border: 1px solid #e4e4e4;
    border-radius: 4px;
    margin-right: 10px;

    &:hover {
      color: @xtxColor;
    }

    &.active {
      background: @xtxColor;
      color: #fff;
      border-color: @xtxColor;
    }

    &.disabled {
      cursor: not-allowed;
      opacity: 0.4;

      &:hover {
        color: #333
      }
    }
  }

  >span {
    margin-right: 10px;
  }
}
</style>